var UserModel = require("../../../models").User;
var ShopModel = require("../../../models").Shop;
var OrderModel = require("../../../models").Order;
var CommentModel = require("../../../models").Comment;
var merge = require('utils-merge');
var co=require('co');
var handleErr=require('../../../libs/handleErr');
exports.openShop=function(req, res, next){
	//未登陆时返回空，已登录返回用户基本数据，目前只有username;
	co(function *() {
		// 模板渲染
		res.json({
		});
	}).catch(handleErr.bind(null, res))
}
exports.index=function(req, res, next){
	//未登陆时返回空，已登录返回用户基本数据，目前只有username;
	var data={};
	res.json(data);
}
exports.myShop=function(req, res, next){
	//未登陆时返回空，已登录返回用户基本数据，目前只有username;
	var data={};
	co(function *() {
		if(req.user) {
			var userBaseInfo = yield UserModel.baseInfo(req.user.name);
			var shop=yield ShopModel.findOne({owner:userBaseInfo._id});
			var order=yield OrderModel.find({shopId:shop._id});
			var comments=yield CommentModel.find({to_shop:shop._id});
			// 模板渲染
			res.json({
				userBaseInfo:userBaseInfo,
				shop:shop,
				comments:comments,
				order:order
			});
		}else{
			res.json({});
		}
	}).catch(handleErr.bind(null, res))
}
exports.shopList=function(req, res, next){
	//未登陆时返回空，已登录返回用户基本数据，目前只有username;
	co(function *() {
		var query={};
		var address;
		if(req.query.address) {
			query.address = new RegExp(req.query.address);
			address=req.query.address;
		}
		var shop=yield ShopModel.find(query);

		res.json({
			shop:shop,
			address:address
		});

	}).catch(handleErr.bind(null, res))
}
exports.shop=function(req, res, next){
	//未登陆时返回空，已登录返回用户基本数据，目前只有username;
	co(function *() {
		var shopId=req.params.id;
		var shop=yield ShopModel.findOne({_id:shopId});
		var comments=yield CommentModel.find({to_shop:shopId});
		if(req.user){
			var userBaseInfo = yield UserModel.baseInfo(req.user.name);
		}
		var data={
			shop:shop,
			comments:comments
		};
		data=merge(data,{userBaseInfo:userBaseInfo});
		res.json(data);

	}).catch(handleErr.bind(null, res))
}
exports.order=function(req, res, next){
	//未登陆时返回空，已登录返回用户基本数据，目前只有username;
	co(function *() {
		var shopId=req.query.shopId;
		var userId=req.query.userId;
		var totalPrice=req.query.totalPrice;
		var totalNum=req.query.totalNum;
		var dish=req.query.dish;
		console.log(dish);
		var shop=yield ShopModel.findOne({_id:shopId});
		var userBaseInfo=yield UserModel.findOne({_id:userId}).select("name role address phone");
		res.json({
			shop:shop,
			userBaseInfo:userBaseInfo,
			dish:dish,
			totalPrice:totalPrice,
			totalNum:totalNum
		})
	}).catch(handleErr.bind(null, res))
}
exports.userCenter=function(req, res, next){
	//未登陆时返回空，已登录返回用户基本数据，目前只有username;
	co(function *() {
		if(req.user){
			var userBaseInfo = yield UserModel.baseInfo(req.user.name);
			var order=yield OrderModel.find({userId:userBaseInfo._id});
			res.json({
				userBaseInfo:userBaseInfo,
				order:order
			})
		}
	}).catch(handleErr.bind(null, res))
}
